<template>
  <div ref="chartContainer" class="chart-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts/core'
import { PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer
])

const props = defineProps({
  chartData: {
    type: Object,
    required: true
  },
  quarter: {
    type: String,
    default: '2024Q1'
  }
})

const chartContainer = ref(null)
let chart: echarts.ECharts | null = null

const COLORS = [
  '#F56C6C', // 红色
  '#E6A23C', // 橙色
  '#909399', // 灰色
  '#67C23A', // 绿色
  '#409EFF', // 蓝色
  '#9B55FF', // 紫色
  '#36CFC9', // 青色
  '#FF9C6E'  // 粉色
]

const initChart = () => {
  if (!chartContainer.value) return
  
  const data = props.chartData[props.quarter] || []
  
  chart = echarts.init(chartContainer.value)
  const option = {
    title: {
      text: '支出构成分析',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      },
      show: false
    },
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#e6e6e6',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      formatter: (params: any) => {
        return `<div style="font-weight:500">${params.name}</div>
                <div style="display:flex;align-items:center;margin-top:5px;">
                  <span style="display:inline-block;width:10px;height:10px;background:${params.color};border-radius:50%;margin-right:8px;"></span>
                  <span>占比: </span>
                  <span style="font-weight:bold;margin-left:5px">${params.percent}%</span>
                </div>`
      }
    },
    legend: {
      orient: 'vertical',
      right: '5%',
      top: 'middle',
      itemWidth: 10,
      itemHeight: 10,
      itemGap: 12,
      icon: 'circle',
      formatter: (name: string) => {
        const item = data.find((d: any) => d.name === name)
        return item ? `${name} (${item.value}%)` : name
      },
      textStyle: {
        fontSize: 12,
        color: '#666'
      }
    },
    series: [
      {
        name: '支出构成',
        type: 'pie',
        center: ['35%', '50%'],
        radius: ['50%', '75%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: false
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        labelLine: {
          show: false
        },
        data: data.map((item: any, index: number) => {
          return {
            name: item.name,
            value: item.value,
            itemStyle: {
              color: COLORS[index % COLORS.length]
            }
          }
        }),
        color: COLORS
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', handleResize)
}

const handleResize = () => {
  chart && chart.resize()
}

const updateChart = () => {
  if (!chart) return
  
  const data = props.chartData[props.quarter] || []
  
  chart.setOption({
    legend: {
      formatter: (name: string) => {
        const item = data.find((d: any) => d.name === name)
        return item ? `${name} (${item.value}%)` : name
      }
    },
    series: [
      {
        data: data.map((item: any, index: number) => {
          return {
            name: item.name,
            value: item.value,
            itemStyle: {
              color: COLORS[index % COLORS.length]
            }
          }
        })
      }
    ]
  })
}

watch(() => props.quarter, () => {
  nextTick(updateChart)
})

watch(() => props.chartData, () => {
  nextTick(updateChart)
}, { deep: true })

onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

// 组件销毁时清理chart
defineExpose({
  dispose: () => {
    if (chart) {
      chart.dispose()
      chart = null
    }
    window.removeEventListener('resize', handleResize)
  }
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style> 